package com.lipaluma.test.db.rules;

import java.lang.reflect.Method;

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.springframework.test.context.TestContextManager;


public class SpringJunit4WithDBMethodRule implements TestRule {

	private TestContextManager testContextManager;
	private final Object target;

	public SpringJunit4WithDBMethodRule(TestContextManager contextManager, Object target) {
		testContextManager = contextManager;
		this.target = target;
	}
	
	@Override
	public Statement apply(Statement base, Description description) {
		return applyMethodRule(base, description, target);
	}
	
	protected Statement applyMethodRule(final Statement base, final Description description, final Object target) {
		
		return new Statement() {
			@Override
			public void evaluate() throws Throwable {
				testContextManager.prepareTestInstance(target);
				Method testMethod = description.getTestClass().getMethod(description.getMethodName());
				testContextManager.beforeTestMethod(target, testMethod);
				Exception thrown = null;
				try {
					base.evaluate();
				} 
				catch (Exception e) {
					thrown = e;
				}
				finally {
					testContextManager.afterTestMethod(target, testMethod, thrown);
					if(thrown != null)
						throw thrown;
				}
			}
		};
	}


}
